package edu.hawaii.examschd.modules;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

  String host = "127.0.0.1";
  int port = 5984;
  Socket connection;
  OutputStream out;
  PrintStream ps;
  InputStream in;

  /**
   * Establish a connection to a server
   * 
   * @return connection the server connection
   */
  protected Socket connect() {
    try {
      connection = new Socket(host, port);
    }
    catch (UnknownHostException uhe) {
      print("Unable to reach host at \"" + host + ":" + port);
      return null;

    }
    catch (IOException ioe) {
      return null;
    }
    if (connection.isConnected()) {
      try {
        out = connection.getOutputStream();
        ps = new PrintStream(out, true); // Second param: auto-flush on
        // write = true
        in = connection.getInputStream();
      }
      catch (IOException ioe) {
        ioe.printStackTrace();
      }
    }
    return connection;
  }

  /**
   * Close the current connection
   * 
   * @return 1 if successful 0 otherwise
   */
  protected int close() {
    try {
      print("Closing connection");
      if (connection.isConnected()) {
        connection.close();
      }
      return 1;
    }
    catch (IOException ioe) {
      ioe.printStackTrace();
    }

    return 0;
  }

  /**
   * Is there a valid connection?
   */
  public boolean isConnected() {
    return connection.isConnected();
  }

  /**
   * Standardized print method Also helps type less
   * 
   * @param s
   */
  private void print(String s) {
    System.out.print(s);
  }
}